package com.wanqing.community.controller;


import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wanqing.community.util.*;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.wanqing.community.bean.DepartmentBean;
import com.wanqing.community.bean.RoleBean;
import com.wanqing.community.bean.UserBean;
import com.wanqing.community.bean.UserDetailBean;
import com.wanqing.community.controller.util.BaseController;
import com.wanqing.community.manager.RoleManager;
import com.wanqing.community.manager.UserDetailManager;
import com.wanqing.community.manager.UserLoginManager;
import com.wanqing.community.singleSignOn.SingleSignOn;

/**
 * 用户表展示层
 * Copyright 2014
 * All right reserved.
 * @version 
 * Company
 */
@Controller
@RequestMapping("userLoginController")
public class UserLoginController extends BaseController{
	
	private static Logger log = Logger.getLogger(UserLoginController.class);
	
	@Resource
	private UserLoginManager userLoginManager;
	@Resource
	private UserDetailManager userDetailManager;
	@Resource
	private RoleManager roleManager;

	
	@RequestMapping(params = "method=login")   
	public String userLogin(HttpServletRequest request,HttpServletResponse response) {
		clearCache(response);
		
		String url = request.getParameter("urlStr");
		
		int retCode = 1;
		String username = null;
		String sessionkey = null;
		String bindid = null;
		if(!(url==null) && !"".equals(url)){
			//提取URL参数
			String[] params = url.split("&");
			String[] keyValues = null;
					
			int i = 0;
			while (i < params.length) {
				if (params[i].startsWith("user=")) {
					keyValues = params[i].split("=");
					username = keyValues[1];
				}
				else if (params[i].startsWith("sessionkey=")) {
					keyValues = params[i].split("=");
					sessionkey = keyValues[1];
				}
				else if (params[i].startsWith("bindid=")) {
					keyValues = params[i].split("=");
					bindid = keyValues[1];
				}
				
				i ++;
			}
		}
		
		// 调用统一认证接口
		if(!(username==null) && !(sessionkey==null) && !equals(bindid==null)) {
			SingleSignOn sso = new SingleSignOn();
			retCode = sso.authSession(username,sessionkey, bindid);
		}
		if(retCode == 0) {
			try{
				UserBean user = this.userLoginManager.findUserByEmail(username);
				HttpSession session = request.getSession();
				session.setAttribute(KeyConstant.USER_SESSION, user);				
				writeCallback(response, "callback", KeyConstant.SUCCESS,"");
			}catch (Exception e) {
				log.error(e.toString());
				writeCallback(response, "callback", KeyConstant.FAIL,e.toString());
			}
		}else{
			String loginName = StringTools.objectToString(request.getParameter("username"));			
			String loginPwd = StringTools.objectToString(request.getParameter("userpwd"));		
			try{
				UserBean user = this.userLoginManager.userLogin(loginName, loginPwd);
				if(null==user || StringTools.isEmptyOrNull(user.getLoginName())){					
					writeCallback(response, "callback", KeyConstant.FAIL,"验证失败，用户名或密码错误！");
				}else{
					HttpSession session = request.getSession();
					session.setAttribute(KeyConstant.USER_SESSION, user);				
					writeCallback(response, "callback", KeyConstant.SUCCESS,"");
				}
			}catch (Exception e) {
				log.error(e.toString());
				writeCallback(response, "callback", KeyConstant.ERRORS,e.toString());
			}
		}
		return null;
	}
	/**
	 * <p>Description:查询管理员列表<p>
	 * <p>modifiContent:<p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=queryUser")
	public String queryUser(HttpServletRequest request,HttpServletResponse response){
		try{
			String loginName = StringTools.objectToString(request.getParameter("loginName"));
			String userName = StringTools.objectToString(request.getParameter("userName"));
			String sex = StringTools.objectToString(request.getParameter("sex"));
			String roleId = StringTools.objectToString(request.getParameter("roleId"));
			String roleName = StringTools.objectToString(request.getParameter("roleName"));
			int pageNo = NumberDealTools.stringTranceInt(request.getParameter("page"), 1);
			int pageSize = NumberDealTools.stringTranceInt(request.getParameter("rows"), KeyConstant.PAGESIZE);
			ConditionParse condParse = new ConditionParse();
			String id = request.getParameter("citysId");
			int orgNature = NumberDealTools.stringTranceInt(request.getParameter("orgNature"));
			if(orgNature == 10){
				if(!id.equals("000")){
					condParse.addCondition("companyId", "=", id);	
				}
			}else if(orgNature == 20) {
				condParse.addCondition("citysId", "=", id);
			}
			condParse.addCondition("T1.ID", "!=", "001");	
			
			//查询条件
			StringBuffer cStr = new StringBuffer();
			if(!loginName.trim().equals("")){
				cStr.append(" AND T1.LOGINNAME LIKE '%"+loginName+"%'");
			}
			if(!userName.trim().equals("")){
				cStr.append(" AND T1.USERNAME LIKE '%"+userName+"%'");
			}
			if(!sex.trim().equals("")){
				cStr.append(" AND T1.SEX = '"+sex+"'");
			}
			if(!roleId.trim().equals("")){
				cStr.append(" AND ud.roleId = '"+roleId+"'");
			}
//			if(!userName.trim().equals("")){
//				cStr.append(" AND T1.USERNAME = '%"+roleName+"%'");
//			}
			if(cStr.length() != 0){
				condParse.addConditionStr(cStr.toString().substring(4));
			}
			
			condParse.addWhereStr();
			int total = this.userLoginManager.getUserCount(condParse,false);
			List<UserBean> list = this.userLoginManager.queryUser(condParse, pageNo, pageSize);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", total);
			map.put("rows", list);	
			String json = StringTools.buildJson(map);			
			writeJson(response, json);
		}catch (Exception e) {
			log.error("查询管理员列表异常："+e.toString());
		}
		return null;
	}
	
	@RequestMapping(params="method=index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
		ModelAndView mav = new ModelAndView();
		String type = request.getParameter("type");
		if("index".equalsIgnoreCase(type)){
			List<RoleBean> list = this.roleManager.listRole();
			mav.addObject("roles", list);
			mav.addObject("m_id", request.getParameter("m_id"));
			mav.setViewName("sys/user/listUser");
		}else if("add".equalsIgnoreCase(type)){
			List<RoleBean> list = this.roleManager.listRole();
			String city = request.getParameter("citysId");
			mav.addObject("roles", list);
			mav.addObject("citysId", request.getParameter("citysId"));
			mav.addObject("citysName", request.getParameter("citysName"));
			mav.setViewName("sys/user/addUser");
		}else if("update".equalsIgnoreCase(type)){
			String id = request.getParameter("id");
			List<RoleBean> list = this.roleManager.listRole();			
			UserBean user = this.userLoginManager.findUserById(id);
			mav.addObject("roles", list);
			mav.addObject("user", user);
			//用户明细
			List<UserDetailBean> udList = this.userDetailManager.findUserDetailById(id);
			mav.addObject("udList", udList);
			String roleIds = "";
			for(int i=0;i<udList.size();i++){
				roleIds += udList.get(i).getRoleId()+",";
			}
			mav.addObject("roleIds", roleIds);
			mav.setViewName("sys/user/updateUser");
		}
		return mav;
	}
	
//	public Object queryProject(String projectCode,int index){
//		Object object = null;
//		if(index==0){
//			object = this.projectStartManager.findProjectStartByProjectCode(projectCode);
//		}
//		return object;
//	}
	
	
	@RequestMapping(params = "method=addUser")   
	public String addUser(HttpServletRequest request,HttpServletResponse response) {				
		try{
			String citysId = StringTools.objectToString(request.getParameter("citysId"));
			String loginName = StringTools.objectToString(request.getParameter("loginName"));
			String loginPwd = StringTools.objectToString(request.getParameter("loginPwd"));
			String userName = StringTools.objectToString(request.getParameter("userName"),"-1");
			String roleId = StringTools.objectToString(request.getParameter("roleId"));
			String sex = StringTools.objectToString(request.getParameter("sex"));
			String mobilePhone = StringTools.objectToString(request.getParameter("mobilePhone"));
			String tel = StringTools.objectToString(request.getParameter("tel"));
			String email = StringTools.objectToString(request.getParameter("email"));
			String otherContactWay = StringTools.objectToString(request.getParameter("otherContactWay"));
			
			String companyId = StringTools.objectToString(request.getParameter("companyId"));
			
			UserBean user = new UserBean();
			String Id = UUID.uuId();
			user.setId(Id);
			user.setLoginName(loginName);
			user.setLoginPwd(MD5.md5Encryption(loginPwd));
			user.setUserName(userName);
			user.setCitysId(citysId);
			user.setRoleId(roleId);	
			user.setSex(sex);
			user.setMobilePhone(mobilePhone);
			user.setTel(tel);
			user.setEmail(email);
			user.setOtherContactWay(otherContactWay);
			user.setCompanyId(companyId);
			
			//添加用户明细
			String roleIds = StringTools.objectToString(request.getParameter("roleIds"));
			List<UserDetailBean> listUserDetail = new ArrayList<UserDetailBean>();
			if(!roleIds.equals("")){
				String[] arrayRoleIds = roleIds.split(",");
				UserDetailBean userDetail = null;
				for(int i=0;i<arrayRoleIds.length;i++){
					userDetail = new UserDetailBean();
					userDetail.setUdId(UUID.uuId());
					userDetail.setRoleId(arrayRoleIds[i]);
					userDetail.setSrDepartmentId(companyId);
					userDetail.setUserId(Id);
					listUserDetail.add(userDetail);
				}
			}
			
			
			ConditionParse condParse = new ConditionParse();
			condParse.addCondition("LOGINNAME", "=", loginName);
			condParse.addWhereStr();
			int total = this.userLoginManager.getUserCount(condParse, true);
			if(total!=0){
				writeText(response, KeyConstant.EXIST);
				return null;
			}
			boolean b = this.userLoginManager.addUserLogin(user);
			this.userDetailManager.addUserDetail(listUserDetail);
			if(b){
				writeText(response, KeyConstant.SUCCESS);
			}else{
				writeText(response, KeyConstant.FAIL);
			}
		}catch (Exception e) {
			log.error(e.toString());
			writeText(response, e.toString());
		}
		return null;
	}
	
	@RequestMapping(params = "method=updateUser")   
	public String updateUser(HttpServletRequest request,HttpServletResponse response) {			
		try{			
			String citysId = StringTools.objectToString(request.getParameter("citysId"));
			String loginName = StringTools.objectToString(request.getParameter("loginName"));			
			String userName = StringTools.objectToString(request.getParameter("userName"),"-1");
			String sex = StringTools.objectToString(request.getParameter("sex"));
			String roleId = StringTools.objectToString(request.getParameter("roleId"));
			String id = StringTools.objectToString(request.getParameter("id"));
			String mobilePhone = StringTools.objectToString(request.getParameter("mobilePhone"));
			String tel = StringTools.objectToString(request.getParameter("tel"));
			String email = StringTools.objectToString(request.getParameter("email"));
			String otherContactWay = StringTools.objectToString(request.getParameter("otherContactWay"));
			String companyId = StringTools.objectToString(request.getParameter("companyId"));
			
			UserBean user = new UserBean();
			user.setId(id);
			user.setLoginName(loginName);			
			user.setUserName(userName);
			user.setSex(sex);
			user.setCitysId(citysId);
			user.setRoleId(roleId);		
			user.setMobilePhone(mobilePhone);
			user.setTel(tel);
			user.setEmail(email);
			user.setOtherContactWay(otherContactWay);
			user.setCompanyId(companyId);
			
			//添加用户明细
			String roleIds = StringTools.objectToString(request.getParameter("roleIds"));
			List<UserDetailBean> listUserDetail = new ArrayList<UserDetailBean>();
			if(!roleIds.equals("")){
				String[] arrayRoleIds = roleIds.split(",");
				UserDetailBean userDetail = null;
				for(int i=0;i<arrayRoleIds.length;i++){
					userDetail = new UserDetailBean();
					userDetail.setUdId(UUID.uuId());
					userDetail.setRoleId(arrayRoleIds[i]);
					userDetail.setSrDepartmentId(companyId);
					userDetail.setUserId(id);
					listUserDetail.add(userDetail);
				}
			}
			
			
			boolean b = this.userLoginManager.updateUserLogin(user);
			this.userDetailManager.deleteUserDetailbyId(id);
			this.userDetailManager.addUserDetail(listUserDetail);
			if(b){
				writeText(response, KeyConstant.SUCCESS);
			}else{
				writeText(response, KeyConstant.FAIL);
			}
		}catch (Exception e) {
			log.error(e.toString());
			writeText(response, e.toString());
		}
		return null;
	}
	
	@RequestMapping(params = "method=deleteUser")   
	public String deleteUser(HttpServletRequest request,HttpServletResponse response) {			
		try{
			String[] roleIds = request.getParameterValues("id[]");	
			if(null==roleIds || roleIds.length==0){
				writeText(response, KeyConstant.EMPTY);
			}else{
				List<String> list = Arrays.asList(roleIds);
				boolean b = this.userLoginManager.deleteUserLogin(list);
				if(b){
					writeText(response, KeyConstant.SUCCESS);
				}else{
					writeText(response, KeyConstant.FAIL);
				}
			}
		}catch (Exception e) {
			log.error(e.toString());
			writeText(response, e.toString());
		}
		return null;
	}
	
	@RequestMapping(params="method=logout")
	public ModelAndView logout(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		session.removeAttribute(KeyConstant.USER_SESSION);
		session.removeAttribute(KeyConstant.FUNC_MENU_BUISS);
		session.removeAttribute(KeyConstant.FUNC_MENU_FUNTREE);
		session.removeAttribute(KeyConstant.LIST_MAIN_MENU);
		session.invalidate();		
		return new ModelAndView(new RedirectView("login.jsp"));
	}
	
	@RequestMapping(params="method=updatePwd")
	public String updatePwd(HttpServletRequest request,HttpServletResponse response){
		try{			
			String loginPwd = StringTools.objectToString(request.getParameter("loginPwd"));
			HttpSession session = request.getSession();
			UserBean users = (UserBean)session.getAttribute(KeyConstant.USER_SESSION);
			String pwd = users.getLoginPwd();
			if(pwd.equals(MD5.md5Encryption(loginPwd))){
				writeText(response, KeyConstant.EXIST);
				return null;
			}
			String id = StringTools.objectToString(request.getParameter("userId"));
			UserBean user = new UserBean();
			user.setId(id);	
			user.setLoginPwd(MD5.md5Encryption(loginPwd));			
			boolean b = this.userLoginManager.updatePwd(user);
			if(b){
				writeText(response, KeyConstant.SUCCESS);
			}else{
				writeText(response, KeyConstant.FAIL);
			}
		}catch (Exception e) {
			log.error(e.toString());
			writeText(response, e.toString());
		}
		return null;
	}
	
	@RequestMapping(params="method=uploadUser")
	public String uploadUser(MultipartHttpServletRequest request,HttpServletResponse response){
		try {
			MultipartFile file = request.getFile("upload");
			if(null!=file && StringTools.isNotEmptyOrNull(file.getOriginalFilename())){
				Workbook workbook = Workbook.getWorkbook(file.getInputStream());
				Sheet sheet = workbook.getSheet(0);
				int rowCount = sheet.getRows();
				List<UserBean> list = new ArrayList<UserBean>();
				UserBean customer = null;
				for (int i = 1;i<rowCount;i++) {
					Cell[] cells = sheet.getRow(i);
					if(null==cells || cells.length==0){
						continue;
					}
					if(StringTools.isEmptyOrNull(cells[0]) || StringTools.isEmptyOrNull(cells[0].getContents()) ){
						continue;
					}
					//第1列 登录名					
					String loginName = "";
					if(!StringTools.isEmptyOrNull(cells[0])){						   
						loginName = StringTools.objectToString(cells[0].getContents());
					}
					//第2列 姓名					
					String userName = "";
					if(!StringTools.isEmptyOrNull(cells[1])){						   
						userName = StringTools.objectToString(cells[1].getContents());
					}
					//第3列 角色名称					
					String roleName = "";
					if(!StringTools.isEmptyOrNull(cells[2])){						   
						roleName = StringTools.objectToString(cells[2].getContents());
					}
					//第4列 部门名称					
					String city = "";
					if(!StringTools.isEmptyOrNull(cells[3])){						   
						city = StringTools.objectToString(cells[3].getContents());
					}
					//第5列 性别					
					String sex = "";
					if(!StringTools.isEmptyOrNull(cells[4])){						   
						sex = StringTools.objectToString(cells[4].getContents());
					}
					if(!StringTools.isEmptyOrNull(loginName)){
						sex = "男".equals(sex)?"1":"0";
						ConditionParse condParse = new ConditionParse();
						condParse.addCondition("ROLENAME", "=", roleName);
						condParse.addWhereStr();						
						List<RoleBean> listrs  = this.roleManager.queryRole(condParse, 1, 10);
						String roleId = "";
						if(null!=listrs && !listrs.isEmpty()){
							roleId = listrs.get(0).getRoleId();
						}
						DepartmentBean depart = this.listCitys(city);
						String citysId = "";
						if(null!=depart){
							citysId = depart.getId();
						}
						customer = new UserBean();
						customer.setCitysId(citysId);
						customer.setId(UUID.uuId());
						customer.setLoginName(loginName);
						customer.setLoginPwd(MD5.md5Encryption("123456"));
						customer.setRoleId(roleId);
						customer.setSex(sex);
						customer.setUserName(userName);
						list.add(customer);
					}
				}
				boolean b = this.userLoginManager.addUserLogin(list);
				if(b){
					writeText(response,  KeyConstant.SUCCESS);
				}else{
					writeText(response, KeyConstant.FAIL);
				}
			}else{
				writeCallback(response, "callback", KeyConstant.ERRORS,"文件没有找到。。。。");
			}
		} catch (Exception e) {			
			log.error("批量导入用户信息出现异常！"+e.toString());
			writeText(response, "系统异常，请与系统维护人员联系"+e.toString());		
		}	
		return null;
	}
	
	@RequestMapping(params="method=exportToExcel")
	public String exportToExcel(HttpServletRequest request,HttpServletResponse response){
		try {
			String[] headers = new String[] { "登录名", "姓名", "部门", "性别", "角色", "手机号", "电话", "电子邮箱", "其它联系方式"};
			OutputStream outputStream = response.getOutputStream();
			response.reset();// 清空输出流
			String downloadFilename = "attachment; filename="+StringTools.strEncode("用户信息.xls");
			response.setHeader("Content-disposition", downloadFilename);// 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=GBK");// 定义输出类型
			// 创建一个xls文件,放入输出流
			WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
			// 创建一个表
			WritableSheet sheet = workbook.createSheet("用户信息", 0);
			for(int i = 0;i<headers.length;i++){
				Label lable = new Label(i,0,headers[i]);
				sheet.addCell(lable);
			}
			ConditionParse condParse = new ConditionParse();
			// 根据业务单据条件模糊查询
			String cityId = request.getParameter("cityId");			
			condParse.addCondition("T1.CITYSID", "=", cityId);
			condParse.addCondition("T1.ID", "!=", "001");
			condParse.addWhereStr();
			List<UserBean> list = this.userLoginManager.queryUser(condParse, 1, 1000);
			if(null!=list && !list.isEmpty()){
				int len = list.size();
				for (int i = 0; i < len; i++) {
					UserBean u = list.get(i);
					sheet.addCell(new Label(0,i+1,u.getLoginName()));
					sheet.addCell(new Label(1,i+1,u.getUserName()));
					sheet.addCell(new Label(2,i+1,u.getCity()));
					sheet.addCell(new Label(3,i+1,"1".equals(u.getSex())?"男":"女"));
					sheet.addCell(new Label(4,i+1,u.getRoleName()));
					sheet.addCell(new Label(5,i+1,u.getMobilePhone()));
					sheet.addCell(new Label(6,i+1,u.getTel()));
					sheet.addCell(new Label(7,i+1,u.getEmail()));
					sheet.addCell(new Label(8,i+1,u.getOtherContactWay()));
				}
			}
			// 写出去
			workbook.write();
			workbook.close();
			outputStream.close(); // 关闭流
		} catch (Exception e) {			
			log.error("导出客户信息出现异常！"+e.toString());
			writeText(response, "系统异常，请与系统维护人员联系"+e.toString());		
		}	
		return null;
	}

}
